package ua.edu.nuos.jeetraining2012.cms.util.template.material;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import ua.edu.nuos.jeetraining2012.cms.entity.UserEntity;
import ua.edu.nuos.jeetraining2012.cms.entity.UsersToCourseEntity;
import ua.edu.nuos.jeetraining2012.cms.entity.UsersToCourseId;
import ua.edu.nuos.jeetraining2012.cms.model.StudentsToCoursesDAO;
import ua.edu.nuos.jeetraining2012.cms.model.exception.DAOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 08.07.13 Time: 10:36
 * @since 1.0
 */
public class SVNTemplate extends DefaultMaterialTemplate {

    private String svnLink;

    private StudentsToCoursesDAO studentsToCoursesDAO;

    private UserEntity user;

    final private static Logger logger = org.slf4j.LoggerFactory.getLogger(SVNTemplate.class);

    // Constructors.
    public SVNTemplate() {
        super();
        templateName = "/view/material/svn.ftl";
    }

    public SVNTemplate(Long courseId) {
        this();
        setCourseId(courseId);

        try {
            InitialContext ic = new InitialContext();

            studentsToCoursesDAO = (StudentsToCoursesDAO) ic.lookup("java:module/StudentsToCoursesDAO");
            logger.debug("Course service injected successful");
        } catch (NamingException e) {
            logger.error("Can't init InitialContext.");
        }

        init();
    }

    @Override
    public Map<String, Object> getMap() {
        logger.debug("Method getMap() - invocation.");

        Map<String, Object> parent = super.getMap();
        Map<String, Object> map = (parent == null)
                ? new HashMap<String, Object>()
                : parent;

        logger.debug("Parent map is {}", map);

        Map<String, Object> i18nMap = (Map) map.get("i18n");
        map.put("i18n", getI18nMap(i18nMap));

        Map<String, Object> innerMap = new HashMap<>();

        map.put("courseId", courseId);
        map.put("courseTitle", courseTitle);
        map.put("courseStartDate", courseStartDate);
        map.put("courseFinishDate", courseFinishDate);
        map.put("syllabusLink", syllabusLink);

        map.put("svn_user", user.getEmail().split("@")[0]);
        map.put("svn_password", user.getSvnPassword());
        map.put("svn_link", svnLink);
        map.put("courses", innerMap);
        map.put("materials_titles", materialTitles);
        map.put("isEnrolled", isEnrolled);

        map.put("hwList", hwList);

        return map;
    }

    private void init() {

        final Subject subject = SecurityUtils.getSubject();
        if (subject != null && subject.isAuthenticated()) {
            user = (UserEntity) subject.getSession().getAttribute("user");
        }

        fetchCourseTitles();
        fetchCourseInfo();

        if (user != null) {
            UsersToCourseId id = new UsersToCourseId(user.getId(), courseId);
            logger.debug("Generating UserToCourseId {}", id);

            try {
                UsersToCourseEntity u2c = studentsToCoursesDAO.findByUsersToCourseId(id);
                logger.debug("u2c entity user_id: {}, course_id: {}", u2c.getUserId(), u2c.getCourseId());
                if (u2c != null) {
                    svnLink = u2c.getSvnLink();
                    logger.debug("Got link: {}", svnLink);
                }
            } catch (DAOException e) {
                logger.error("Can't fetch relation user to course. Error: {} ", e.getMessage());
            }
        }
    }
}
